package br.com.dataphonebr.util;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;

import br.com.dataphonebr.R;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Vibrator;
import android.preference.PreferenceManager;
import android.widget.Toast;

@SuppressLint("SimpleDateFormat")
public class Util {
	
	public static final String COMING_FROM = "COMING_FROM";
	
	public void vibrate(Context context){
		boolean vibrate = (getPreferences(context).getBoolean("notifications_new_message_vibrate", false));
		if (vibrate){
			Vibrator rr = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
			long milliseconds = 500; 
			rr.vibrate(milliseconds);         
		}
	}

	public void showToastMessage(int message, Context context){
		String error = context.getString(message);
		Toast toast = Toast.makeText(context, error, Toast.LENGTH_SHORT);
		toast.show();
	}

	public void showToastMessage(String message, Context context){
		Toast toast = Toast.makeText(context, message, Toast.LENGTH_SHORT);
		toast.show();
	}

	public void showToastMessageLong(String message, Context context){
		Toast toast = Toast.makeText(context, message, Toast.LENGTH_LONG);
		toast.show();
	}
	
    public SharedPreferences getPreferences(Context context){
    	SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
    	return preferences;
    }
    
    public final static boolean isValidEmail(CharSequence target) {
        if (target == null) {
            return false;
        } else {
            return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
        }
    }
    
    public static String abreviar(int limite, String valor){
    	if (valor != null && !valor.isEmpty()){
    		if (valor.length() > limite)
    			valor = valor.substring(0, limite)+"...";
    	}
    	return valor;
    }
    
    public Date stringToDate(String dateStr) throws ParseException{
    	if (dateStr != null && !dateStr.isEmpty()){
	    	DateFormat formatter; 
	    	Date date; 
	    	formatter = DateFormat.getDateInstance(DateFormat.MEDIUM, new Locale("pt", "BR"));
	    	date = formatter.parse(dateStr);
	    	return date;
    	}
    	return null;
    }

    public BigDecimal stringToDecimal(String valorStr){
    	if (valorStr != null && !valorStr.isEmpty()){
    		BigDecimal valor = new BigDecimal(valorStr);
    		return valor.setScale(2, RoundingMode.HALF_EVEN);
    	}
    	return null;
    }
    
    public Date stringToTime(String timeStr) throws ParseException{
    	if (timeStr != null && !timeStr.isEmpty()){
    		DateFormat formatter; 
    		Date date; 
    		formatter = new SimpleDateFormat("HH:mm");
    		date = formatter.parse(timeStr);
    		return date;
    	}
    	return null;
    }
    
    public String dateToStringSql(Date date){
    	if (date != null){
    		DateFormat formatter = new SimpleDateFormat("yy-MM-yyyy");
    		String dateStr = formatter.format(date);
    		return dateStr;
    	}
    	return "";
    }
    
    public String dateToString(Date date){
    	if (date != null){
	    	DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy", new Locale("pt","BR"));
	    	String dateStr = formatter.format(date);
	    	return dateStr;
    	}
    	return "";
    }

    public String dateTimeToString(Date date){
    	if (date != null){
    		DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy HH:mm", new Locale("pt","BR"));
    		String dateStr = formatter.format(date);
    		return dateStr;
    	}
    	return "";
    }
    
    public String dateToStringMedium(Date date){
    	if (date != null){
    		DateFormat formatter; 
    		formatter = new SimpleDateFormat("dd 'de' MMMM 'de' yyyy", new Locale("pt","BR"));
    		String dateStr = formatter.format(date);
    		return dateStr;
    	}
    	return "";
    }

    public String dateTimeToStringMedium(Date date){
    	if (date != null){
    		DateFormat formatter; 
    		formatter = new SimpleDateFormat("dd 'de' MMMM 'de' yyyy, HH:mm", new Locale("pt","BR"));
    		String dateStr = formatter.format(date);
    		return dateStr;
    	}
    	return "";
    }
    
    public String dateToStringFull(Date date, Context context){
    	if (date != null){
    		String dateStr = this.dateToStringMedium(date);
    		String diaDaSemana = getWeekDay(date, context);
    		dateStr = diaDaSemana+", "+dateStr;
    		return dateStr;
    	}
    	return "";
    }
    
    public Locale getCurrentyLocale(Context context){
    	return context.getResources().getConfiguration().locale;
    }
    
    public String getWeekDay(Date data, Context context){ 
    	String language = getCurrentyLocale(context).getLanguage();
    	String country = getCurrentyLocale(context).getCountry();
    	GregorianCalendar calendar = new GregorianCalendar(new Locale(language, country)); 
    	calendar.setTime(data); 
    	String[] diaSemana = new String[]{	context.getString(R.string.sunday)
						    			, 	context.getString(R.string.monday)
						    			, 	context.getString(R.string.tuesday)
						    			, 	context.getString(R.string.wednesday)
						    			, 	context.getString(R.string.thursday)
						    			, 	context.getString(R.string.friday)
						    			, 	context.getString(R.string.saturday) }; 
    	return diaSemana[calendar.get(GregorianCalendar.DAY_OF_WEEK)-1]; 
    	} 
    
    public String timeToString(Date date){
    	if (date != null){
	    	DateFormat formatter; 
	    	formatter = new SimpleDateFormat("HH:mm");
	    	String dateStr = formatter.format(date);
	    	return dateStr;
    	}
    	return "";
    }
    
    public Date addDateAndTime(Date date, Date time){
    	if (date != null && time != null){
    		Calendar calendarDate = Calendar.getInstance();
    		calendarDate.setTime(date);
    		Calendar calendarTime = Calendar.getInstance();
    		calendarTime.setTime(time);
    		Calendar calendarDateTime = Calendar.getInstance();
    		int day = calendarDate.get(Calendar.DATE);
    		int month = calendarDate.get(Calendar.MONTH);
    		int year = calendarDate.get(Calendar.YEAR);
    		int hourOfDay = calendarTime.get(Calendar.HOUR_OF_DAY);
    		int minute = calendarTime.get(Calendar.MINUTE);
    		calendarDateTime.set(year, month, day, hourOfDay, minute, 0);
    		return calendarDateTime.getTime();
    	}
    	if (date != null)
    		return date;
    	if (time != null)
    		return time;
    	return null;
    }

    public Date dateTimeToDate(Date date){
    	if (date != null){
        	SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");     
    		try {
    			Date date1 = sdf.parse(dateToString(date));
    			return date1;
    		} catch (ParseException e) {
    			e.printStackTrace();
    		}
    	}
    	return null;
    }

    public Date dateTimeToTime(Date date){
    	if (date != null){
    		Calendar calendarDateTime = Calendar.getInstance();
    		calendarDateTime.setTime(date);
    		Calendar calendarDate = Calendar.getInstance();
    		int hourOfDay = calendarDateTime.get(Calendar.HOUR_OF_DAY);
    		int minute = calendarDateTime.get(Calendar.MINUTE);
    		calendarDateTime.set(0, 0, 0, hourOfDay, minute, 0);
    		return calendarDate.getTime();
    	}
    	return null;
    }
    
    public Long diffInDays(Date initialDate, Date finalDate){  
    	SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");     
		try {
			Date date1 = sdf.parse(dateToString(initialDate));
			Date date2 = sdf.parse(dateToString(finalDate));
			long differenceMilliSeconds = date2.getTime() - date1.getTime();
			Long result = (differenceMilliSeconds/1000/60/60/24);
			if (result > 0)
				return result;
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return 0L;
    }

    public Long diffInHours(Date initialDate, Date finalDate){  
    	SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm");     
    	try {
    		Date date1 = sdf.parse(dateTimeToString(initialDate));
    		Date date2 = sdf.parse(dateTimeToString(finalDate));
    		long differenceMilliSeconds = date1.getTime() - date2.getTime();
    		Long result = (differenceMilliSeconds/1000/60/60);
    		if (result > 0)
    			return result;
    	} catch (ParseException e) {
    		e.printStackTrace();
    	}
    	return 0L;
    }

    public Long diffInMinutes(Date initialDate, Date finalDate){  
    	SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm");     
    	try {
    		Date date1 = sdf.parse(dateTimeToString(initialDate));
    		Date date2 = sdf.parse(dateTimeToString(finalDate));
    		long differenceMilliSeconds = date1.getTime() - date2.getTime();
    		Long result = (differenceMilliSeconds/1000/60);
    		if (result > 0)
    			return result;
    	} catch (ParseException e) {
    		e.printStackTrace();
    	}
    	return 0L;
    }
    
    public String getLabelDiffTimeToString(Date initialDate, Date finalDate){
    	String label = "";
    	long diffInHours = this.diffInHours(initialDate, finalDate);
    	long diffInMinutes = this.diffInMinutes(initialDate, finalDate);
    	if (diffInHours > 0){
    		label = diffInHours+(diffInHours==1L?" hora ":" horas");
    		if (diffInMinutes > 0){
	    		diffInMinutes = diffInMinutes-(diffInHours*60);
	    		if (diffInMinutes > 0){
	    			label = label+" e "+diffInMinutes+(diffInMinutes==1L?" minuto ":" minutos");
	    		}
    		}
    	} else {
    		if (diffInMinutes > 0){
    			label = diffInMinutes+(diffInMinutes==1L?" minuto ":" minutos");
    		}
    	}
    	return label;
    }

    public String getLabelDiffDaysToString(Date initialDate, Date finalDate){
    	String label = "";
    	long diffInDays = this.diffInDays(finalDate, initialDate);
    	long diffInHours = this.diffInHours(initialDate, finalDate);
    	if (diffInDays > 0){
    		label = diffInDays+(diffInDays==1L?" dia ":" dias");
    		if (diffInHours > 0){
    			diffInHours = diffInHours-(diffInDays*60);
    			if (diffInHours > 0){
    				label = label+" e "+diffInHours+(diffInHours==1L?" hora ":" horas");
    			}
    		}
    	} else {
    		if (diffInHours > 0){
    			label = diffInHours+(diffInHours==1L?" hora ":" horas");
    		}
    	}
    	return label;
    }
    
	public boolean time1IsHigherThanTime2(Date time1, Date time2 ){
		if (time1 != null && time2 != null){
			Calendar calendarTime1 = Calendar.getInstance();
			calendarTime1.setTime(time1);
			Calendar calendarTime2 = Calendar.getInstance();
			calendarTime2.setTime(time2);
			if (calendarTime1.get(Calendar.HOUR_OF_DAY) > calendarTime2.get(Calendar.HOUR_OF_DAY)){
				return true;
			}
			if (calendarTime1.get(Calendar.HOUR_OF_DAY) == calendarTime2.get(Calendar.HOUR_OF_DAY) && calendarTime1.get(Calendar.MINUTE) > calendarTime2.get(Calendar.MINUTE)){
				return true;
			}
		}
		return false;
	}

	public boolean date1IsHigherOrEqualThanDate2(Date date1, Date date2){
		if (date1 != null && date2 != null){
			Calendar calendarDate1 = Calendar.getInstance();
			calendarDate1.setTime(date1);
			Calendar calendarDate2 = Calendar.getInstance();
			calendarDate2.setTime(date2);
			if (calendarDate1.get(Calendar.YEAR) >= calendarDate2.get(Calendar.YEAR)){
				if (calendarDate1.get(Calendar.MONTH) >= calendarDate2.get(Calendar.MONTH)){
					if (calendarDate1.get(Calendar.DATE) >= calendarDate2.get(Calendar.DATE)){
						return true;
					}
				}
			}
		}
		return false;
	}
	
	public boolean date1IsEqualThanDate2(Date date1, Date date2){
		if (date1 != null && date2 != null){
			Calendar calendarDate1 = Calendar.getInstance();
			calendarDate1.setTime(date1);
			Calendar calendarDate2 = Calendar.getInstance();
			calendarDate2.setTime(date2);
			if (calendarDate1.get(Calendar.YEAR) == calendarDate2.get(Calendar.YEAR)){
				if (calendarDate1.get(Calendar.MONTH) == calendarDate2.get(Calendar.MONTH)){
					if (calendarDate1.get(Calendar.DATE) == calendarDate2.get(Calendar.DATE)){
						return true;
					}
				}
			}
		}
		return false;
	}
	
    public Boolean getBoolValue(Boolean bool){
    	if (bool != null)
    		return bool;
    	return false;
    }
    
    public Calendar getCurrentDate(){
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(new Date());
		calendar.set(Calendar.HOUR, 0);
		calendar.set(Calendar.MINUTE, 0);
		calendar.set(Calendar.SECOND, 0);
		return calendar;
    }

    public Date getCurrentTime(){
    	Calendar calendar = Calendar.getInstance();
    	calendar.setTime(new Date());
    	calendar.set(Calendar.SECOND, 0);
    	return calendar.getTime();
    }
    
}
